package com.kxmalls.templates.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kxmalls.common.core.domain.PageQuery;
import com.kxmalls.common.core.page.TableDataInfo;
import com.kxmalls.common.enums.ShopCommonEnum;
import com.kxmalls.common.exception.ServiceException;
import com.kxmalls.common.utils.StringUtils;
import com.kxmalls.system.domain.bo.SysRegionBo;
import com.kxmalls.system.domain.bo.SysRegionChildrenBo;
import com.kxmalls.system.domain.bo.SysRegionInfoBo;
import com.kxmalls.templates.domain.WmTemplates;
import com.kxmalls.templates.domain.WmTemplatesItem;
import com.kxmalls.templates.domain.WmTemplatesRegion;
import com.kxmalls.templates.domain.bo.AppointInfoBo;
import com.kxmalls.templates.domain.bo.WmTemplatesBo;
import com.kxmalls.templates.domain.vo.WmTemplatesVo;
import com.kxmalls.templates.mapper.WmTemplatesItemMapper;
import com.kxmalls.templates.mapper.WmTemplatesMapper;
import com.kxmalls.templates.mapper.WmTemplatesRegionMapper;
import com.kxmalls.templates.service.IWmTemplatesService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 运费模板Service业务层处理
 *
 * @author kxmalls
 * @date 2023-02-08
 */
@RequiredArgsConstructor
@Service
public class WmTemplatesServiceImpl implements IWmTemplatesService {

    private final WmTemplatesMapper baseMapper;

    private final WmTemplatesItemMapper baseMapperItem;

    private final WmTemplatesRegionMapper baseMapperRegion;

    /**
     * 查询运费模板
     */
    @Override
    public WmTemplatesVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询运费模板列表
     */
    @Override
    public TableDataInfo<WmTemplatesVo> queryPageList(WmTemplatesBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<WmTemplates> lqw = buildQueryWrapper(bo);
        Page<WmTemplatesVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询运费模板列表
     */
    @Override
    public List<WmTemplatesVo> queryList(WmTemplatesBo bo) {
        LambdaQueryWrapper<WmTemplates> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<WmTemplates> buildQueryWrapper(WmTemplatesBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<WmTemplates> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), WmTemplates::getName, bo.getName());
        lqw.eq(bo.getType() != null, WmTemplates::getType, bo.getType());
        lqw.eq(bo.getAppoint() != null, WmTemplates::getAppoint, bo.getAppoint());
        lqw.eq(bo.getIsDel() != null, WmTemplates::getIsDel, bo.getIsDel());
        lqw.eq(bo.getSort() != null, WmTemplates::getSort, bo.getSort());
        return lqw;
    }

    /**
     * 新增运费模板
     */
    @Override
    public Boolean insertAndupdateByBo(WmTemplatesBo bo) {

        if (ShopCommonEnum.ENABLE_1.getValue().equals(bo.getAppoint())
            && bo.getAppointInfo().isEmpty()) {
            throw new ServiceException("请指定包邮地区");
        }
        WmTemplates add = BeanUtil.toBean(bo, WmTemplates.class);
        if (bo.getId() != null && bo.getId() > 0) {
            baseMapper.updateById(add);
        } else {
            baseMapper.insert(add);
        }

        this.saveRegion(bo, bo.getId());
        this.saveFreeReigion(bo, bo.getId());

        return true;
    }

    /**
     * 保存模板设置的区域价格
     *
     * @param wmTemplatesBo
     * @param tempId        运费模板id
     */
    private void saveRegion(WmTemplatesBo wmTemplatesBo, Long tempId) {
        Long count = baseMapperRegion.selectCount(new LambdaQueryWrapper<WmTemplatesRegion>()
            .eq(WmTemplatesRegion::getTempId, tempId));
        if (count > 0) {
            baseMapperRegion.delete(new LambdaQueryWrapper<WmTemplatesRegion>()
                .eq(WmTemplatesRegion::getTempId, tempId));
        }

        List<WmTemplatesRegion> wmTemplatesRegions = new ArrayList<>();


        List<SysRegionInfoBo> regionInfo = wmTemplatesBo.getRegionInfo();


        for (SysRegionInfoBo regionInfoDto : regionInfo) {
            String uni = IdUtil.simpleUUID();
            if (regionInfoDto.getRegion() != null && !regionInfoDto.getRegion().isEmpty()) {
                for (SysRegionBo regionDto : regionInfoDto.getRegion()) {
                    if (regionDto.getChildren() != null && !regionDto.getChildren().isEmpty()) {
                        for (SysRegionChildrenBo childrenDtp : regionDto.getChildren()) {
                            WmTemplatesRegion shippingTemplatesRegion = WmTemplatesRegion.builder()
                                .tempId(tempId)
                                .first(new BigDecimal(regionInfoDto.getFirst()))
                                .firstPrice(new BigDecimal(regionInfoDto.getPrice()))
                                .continues(new BigDecimal(regionInfoDto.get_continue()))
                                .continuePrice(new BigDecimal(regionInfoDto.getContinue_price()))
                                .type(wmTemplatesBo.getType())
                                .uniqid(uni)
                                .provinceId(regionDto.getCityId())
                                .cityId(Long.valueOf(childrenDtp.getCityId()))
                                .build();
                            wmTemplatesRegions.add(shippingTemplatesRegion);
                        }
                    } else {
                        WmTemplatesRegion shippingTemplatesRegion = WmTemplatesRegion.builder()
                            .tempId(tempId)
                            .first(new BigDecimal(regionInfoDto.getFirst()))
                            .firstPrice(new BigDecimal(regionInfoDto.getPrice()))
                            .continues(new BigDecimal(regionInfoDto.get_continue()))
                            .continuePrice(new BigDecimal(regionInfoDto.getContinue_price()))
                            .type(wmTemplatesBo.getType())
                            .uniqid(uni)
                            .provinceId(regionDto.getCityId())
                            .build();
                        wmTemplatesRegions.add(shippingTemplatesRegion);
                    }
                }
            }
        }

        if (wmTemplatesRegions.isEmpty()) {
            throw new ServiceException("请添加区域");
        }
        baseMapperRegion.insertOrUpdateBatch(wmTemplatesRegions);
    }

    /**
     * 保存包邮区域
     *
     * @param wmTemplatesBo ShippingTemplatesDto
     * @param tempId        模板id
     */
    private void saveFreeReigion(WmTemplatesBo wmTemplatesBo, Long tempId) {

        if (wmTemplatesBo.getAppointInfo() == null
            || wmTemplatesBo.getAppointInfo().isEmpty()) {
            return;
        }

        Long count = baseMapperItem.selectCount(new LambdaQueryWrapper<WmTemplatesItem>()
            .eq(WmTemplatesItem::getTempId, tempId));
        if (count > 0) {
            baseMapperItem.delete(new LambdaQueryWrapper<WmTemplatesItem>()
                .eq(WmTemplatesItem::getTempId, tempId));
        }

        List<WmTemplatesItem> shippingTemplatesFrees = new ArrayList<>();


        List<AppointInfoBo> appointInfo = wmTemplatesBo.getAppointInfo();
        for (AppointInfoBo appointInfoBo : appointInfo) {
            String uni = IdUtil.simpleUUID();

            if (appointInfoBo.getPlace() != null && !appointInfoBo.getPlace().isEmpty()) {
                for (SysRegionBo regionBo : appointInfoBo.getPlace()) {
                    if (regionBo.getChildren() != null && !regionBo.getChildren().isEmpty()) {
                        for (SysRegionChildrenBo childrenDto : regionBo.getChildren()) {
                            WmTemplatesItem shippingTemplatesFree = WmTemplatesItem.builder()
                                .tempId(tempId)
                                .number(new BigDecimal(appointInfoBo.getA_num()))
                                .price(new BigDecimal(appointInfoBo.getA_price()))
                                .type(wmTemplatesBo.getType())
                                .uniqid(uni)
                                .provinceId(regionBo.getCityId())
                                .cityId(Long.valueOf(childrenDto.getCityId()))
                                .build();
                            shippingTemplatesFrees.add(shippingTemplatesFree);
                        }
                    }
                }
            }
        }


        if (shippingTemplatesFrees.isEmpty()) {
            throw new ServiceException("请添加包邮区域");
        }
        baseMapperItem.insertBatch(shippingTemplatesFrees);
    }

    /**
     * 修改运费模板
     */
    @Override
    public Boolean updateByBo(WmTemplatesBo bo) {
        WmTemplates update = BeanUtil.toBean(bo, WmTemplates.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(WmTemplates entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除运费模板
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
